#pragma once

#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>

template <typename T>
class BlockQueue
{
private:
    bool IsFull()
    {
        return _block_queue.size() == _cap;
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }

public:
    BlockQueue(int cap)
        : _cap(cap), _product_wait_num(0), _consumer_wait_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_product_cont, nullptr);
        pthread_cond_init(&_consum_cont, nullptr);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cont);
        pthread_cond_destroy(&_consum_cont);
    }
    void Enqueue(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull()) // 得用while不停判断
        {
            std::cout << "Full" << std::endl;
            // 生产线程去等待,是在临界区中休眠的！你现在还持有锁呢！！！
            // 1. pthread_cond_wait调用是: a. 让调用线程等待 b. 自动释放曾经持有的_mutex锁 c. 当条件满足，线程唤醒，pthread_cond_wait要求线性
            // 必须重新竞争_mutex锁，竞争成功，方可返回！！！
            usleep(1000);
            _product_wait_num++;
            pthread_cond_wait(&_product_cont, &_mutex);
            _product_wait_num--;
        }
        _block_queue.push(in);
        if (_consumer_wait_num > 0)
        { // 消费者等待数量
            if (_consumer_wait_num > 0)
            {
                std::cout << ">0" << std::endl;
                pthread_cond_signal(&_consum_cont); // 给消费者发信号
            }
            pthread_mutex_unlock(&_mutex);
        }
    }
    void Pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            usleep(1000);
            std::cout << "empty" << std::endl;
            _consumer_wait_num++;
            pthread_cond_wait(&_consum_cont, &_mutex);
            std::cout << "wait--" << std::endl;
            _consumer_wait_num--;
        }
        *out = _block_queue.back();
        _block_queue.pop();
        if (_product_wait_num > 0)
        { // 生产者等待数量
            if (_product_wait_num > 0)
            {
                std::cout << ">0" << std::endl;
                pthread_cond_signal(&_product_cont); // 给生产者发信号
            }
            pthread_mutex_unlock(&_mutex);
        }
    }

private:
    std::queue<T> _block_queue;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _product_cont;
    pthread_cond_t _consum_cont;

    int _product_wait_num;
    int _consumer_wait_num;
};
